#!/bin/bash

function log {
        echo "$1: $0: $2" >&2
}

log INFO "Initializing casperd"

# Loading configuration
if [ -f ${CASPER_CONF_DIR}/casperd.conf ]; then
	source ${CASPER_CONF_DIR}/casperd.conf
elif [ -f etc/casperd.conf ]; then
	source etc/casperd.conf
fi

# System clear
log INFO "Cleaning system..."
# Setting CASPER_RUN_DIR for run
if [ ! -d ${CASPER_RUN_DIR} ]; then
        mkdir ${CASPER_RUN_DIR}
fi
rm -rf ${CASPER_RUN_DIR}/*
if [ -d $CASPER_WORK_DIR ]; then
        rm -Rf $CASPER_WORK_DIR/*
fi

# Setting configuration variables
log INFO "Setting main configuration variables..."
echo variables set CASPER_RUN_DIR ${CASPER_RUN_DIR}
echo variables set CASPER_WORK_DIR ${CASPER_WORK_DIR}
echo variables set CASPER_POOL_DIR ${CASPER_POOL_DIR}
echo variables set CASPER_FINAL_DIR ${CASPER_FINAL_DIR}

log INFO "Setting PATH..."
echo variables set PATH ${PATH}:${CASPER_ROOT_DIR}/bin/

NODES_USE=
for i in `seq 0 $((${#NODES_NAMES[@]}-1))`
do
        NODES_USE="${NODES_USE} $i"
done
echo variables set NODES_USE ${NODES_USE}

# Loading modules
log INFO "Loading configured modules..."
for mod in $MODULES_LOAD
do
        if [ -x scripts/modules/mod_${MODULES_NAMES[${mod}]}_init.sh ]; then
			scripts/modules/mod_${MODULES_NAMES[${mod}]}_init.sh
        fi
        echo modules load ${MODULES_FILES[$mod]}
        if [ -x scripts/modules/mod_${MODULES_NAMES[${mod}]}_post.sh ]; then
        	scripts/modules/mod_${MODULES_NAMES[${mod}]}_post.sh
        fi
done
